package com.yoome.easyrpc.biz.registry.zookeeper;

import com.yoome.easyrpc.common.consts.Symbols;
import com.yoome.easyrpc.common.enums.ErrorCode;
import com.yoome.easyrpc.biz.loadbalance.LoadBalance;
import com.yoome.easyrpc.biz.registry.ServiceDiscovery;
import com.yoome.easyrpc.common.utils.CuratorUtil;
import com.yoome.easyrpc.common.utils.EasyRpcException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.List;

@Slf4j
@Component
public class ZkServiceDiscovery implements ServiceDiscovery {

    @Autowired
    private LoadBalance loadBalance;

    public InetSocketAddress discoverService(String serviceName) {
        CuratorFramework client = CuratorUtil.getClient();
        List<String> servicePaths = CuratorUtil.getChildNodes(client, serviceName);
        if (CollectionUtils.isEmpty(servicePaths)) {
            log.info("not find available service!");
             throw new EasyRpcException(ErrorCode.SERVICE_NOT_FOUND);
        }

        String servicePath = loadBalance.selectService(servicePaths, serviceName);
        String[] address = servicePath.split(Symbols.COLON);
        if (address.length < 2) {
            log.info("service address invalid with name:{}", servicePath);
            throw new EasyRpcException(ErrorCode.SERVICE_ADDRESS_INVALID);
        }

        String host = address[0];
        Integer port = null;
        try {
            port = Integer.parseInt(address[1]);
        } catch (NumberFormatException e) {
            log.info("service address invalid with name:{}", servicePath);
            throw new EasyRpcException(ErrorCode.SERVICE_ADDRESS_INVALID);
        }
        return new InetSocketAddress(host, port);
    }
}
